package com.iteaj.iot.server.component;

import com.iteaj.iot.config.ConnectProperties;
import com.iteaj.iot.server.DeviceServerComponent;
import com.iteaj.iot.server.ServerMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * create time: 2021/2/21
 *  适配{@link ByteToMessageDecoder}解码器到服务组件{@link DeviceServerComponent}
 * @author iteaj
 * @since 1.0
 */
public abstract class ByteToMessageDecoderComponent<M extends ServerMessage> extends SocketDecoderComponent<M> {

    public ByteToMessageDecoderComponent(ConnectProperties connectProperties) {
        super(connectProperties);
    }

    @Override
    public ChannelInboundHandlerAdapter getMessageDecoder() {
        return new ByteToMessageDecoderWrapper();
    }

    /**
     * 自定义解码
     * @param ctx
     * @param in
     * @return
     * @throws Exception
     */
    @Override
    public abstract M decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception;

    protected class ByteToMessageDecoderWrapper extends ByteToMessageDecoder {

        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            List<M> decodes = ByteToMessageDecoderComponent.this.decodes(ctx, in);
            if(decodes != null) {
                out.addAll(decodes);
            }
        }
    }
}
